package com.example.foreapp;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DbOpenHelper extends SQLiteOpenHelper{
	
	private final static String DB_NAME="foreapp.sdb";
	private final static int DB_VERSION=3;

	public DbOpenHelper(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		db.execSQL("create table apps (_id integer primary key autoincrement,time text,applabel text, classname text,packagename text,favor char(1))");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		db.execSQL("drop table if exists apps");
		onCreate(db);
	}
	
	public long insertRcode(String time,String label,String pkg,String classname){
		SQLiteDatabase db=getWritableDatabase();
		long raw=0;
		ContentValues cv=new ContentValues();
		cv.put("time", time);
		cv.put("applabel", label);
		cv.put("classname", classname);
		cv.put("packagename", pkg);
		raw=db.insert("apps", null, cv);
		db.close();
		return raw;
	}
	
	public Cursor query(String order,boolean asc){
		SQLiteDatabase db=getReadableDatabase();
		String sql="select * from apps order by "+order+" "+(asc?"asc":"desc");
		
		Cursor cursor=db.rawQuery(sql,null);
		return cursor;
	}
	
	public boolean findActivity(ActivityInfo info){
		SQLiteDatabase db=getReadableDatabase();
		String sql="select * from apps where classname=? and packagename=?";
		Cursor c=db.rawQuery(sql, new String[]{info.getClassName(),info.getPkgName()});
		boolean f= c.getCount()>0;
		db.close();
		return f;
	}
	
	public long updateRecode(ActivityInfo info){
		SQLiteDatabase db=getWritableDatabase();
		ContentValues cv=new ContentValues();
		cv.put("time", info.getTime());
		cv.put("favor", info.isFavor()?"t":"f");
		long raw=db.update("apps", cv, "classname=? and packagename=?", new String[]{info.getClassName(),info.getPkgName()});
		return raw;
	}

}
